const http = require("http");
const url = require("url");
const fs = require("fs");
const querystring = require("querystring");
 
const server = http.createServer();
const HtmlDir = __dirname + "/html/";

server.on('request', function (req, res) {
    let urlStr = url.parse(req.url);
    // console.log(urlStr);
    switch (urlStr.pathname) {
        case '/':
            // 首页
            // res.writeHead(200, {
            //     'content-type': 'text/html;charset=utf-8'
            // });
            // res.end('<h1>这是首页</h1>');
            sendData(HtmlDir + 'index.html', req, res);
            break;
        case '/user':
            // res.writeHead(201, {
            //     'content-type': 'text/html;charset=utf-8'
            // });
            // res.end('<h1>这是首页</h1>');
            sendData(HtmlDir + 'user.html', req, res)
            break;
        case '/login':
            sendData(HtmlDir + 'login.html', req, res)
            break;
        case '/login/check':
           console.log(req.method);
           console.log(querystring.parse(urlStr.query));
            break;
        default:
            break;
    }
});

function sendData(file, req, res) {
    fs.readFile(file, function (err, data) {
        if (err) {
            res.writeHead(404, {
                'content-type': 'text/html;charset:utf-8'
            });
            res.end("<h1>页面出错了</h1>");
        } else {
            res.writeHead(404, {
                'content-type': 'text/html;charset:utf-8'
            });
            res.end(data);
        }
    })
}

server.listen(8005);